package com.cysd.ewmxns.ui.activity

import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.cszy.ewmxns.base.BaseVMActivity

import com.cysd.ewmxns.service.RecognizeService
import com.cysd.ewmxns.utils.ClipboardUtils
import com.cysd.ewmxns.utils.FileUtil
import com.cysd.ewmxns.viewmodel.MainViewModel
import com.google.gson.Gson
import qrrspeeelild.rqrc0ode.andro0ild.R
import qrrspeeelild.rqrc0ode.andro0ild.databinding.ActivityOcrResultBinding
import org.json.JSONObject


class OcrResultActivity : BaseVMActivity<MainViewModel, ActivityOcrResultBinding>() {
    override fun initView(savedInstanceState: Bundle?) {
        mBinding.headTitle.headCenterTitle.text = "提取结果"
    }

    override fun initData() {
            RecognizeService.recGeneralBasic(this,
                FileUtil.getSaveFile(this).absolutePath,
                object : RecognizeService.ServiceListener {  // 去掉括号
                    override fun onResult(result: String?) {
                        Log.e("qin", "识别结果：$result")
                        mBinding.tvResult.text = parseWithOrgJson(result!!)
                    }
                })

        Glide.with(this)
            .load( FileUtil.getSaveFile(this).absolutePath)
            .placeholder(R.mipmap.ic_launcher)
            .error(R.mipmap.ic_launcher)

            .into(mBinding.ivResult)
    }

    override fun initListener() {
        mBinding.headTitle.headBack.setOnClickListener {
            finish()
        }

        mBinding.tvCopy.setOnClickListener {
            ClipboardUtils.copyTextFromTextView(this, mBinding.tvResult) // 默认显示 Toast
        }
    }
    fun parseWithOrgJson(json: String): String {
        if (json.isBlank()) {
            return "暂无识别内容"
        }
        try {
            val jsonObj = JSONObject(json)

            // 检查是否有 words_result 字段
            if (!jsonObj.has("words_result") || jsonObj.isNull("words_result")) {
                return "暂无识别内容"
            }

            val wordsArray = jsonObj.getJSONArray("words_result")

            // 检查数组是否为空
            if (wordsArray.length() == 0) {
                return "暂无识别内容"
            }

            return (0 until wordsArray.length())
                .mapNotNull { index ->
                    try {
                        val wordObj = wordsArray.getJSONObject(index)
                        // 检查是否有 words 字段且不为空
                        if (wordObj.has("words") && !wordObj.isNull("words")) {
                            wordObj.getString("words")
                        } else {
                            null
                        }
                    } catch (e: Exception) {
                        null // 如果获取某个单词失败，返回 null 跳过
                    }
                }
                .filter { it.isNotBlank() } // 过滤空字符串
                .joinToString(" ")
                .ifBlank { "暂无识别内容" } // 如果最终结果为空字符串，返回默认值

        } catch (e: Exception) {
            // 处理 JSON 解析异常
            return "解析错误: ${e.message}"
        }
    }
}